/*
* @Author: dengjiayao
* @Date:   2017-04-10 14:57:41
* @Last Modified by:   dengjiayao
* @Last Modified time: 2017-04-24 09:36:19
*/

import { modal } from 'vue-strap'
import { showMsg, insertBetaAd, updateBetaAd } from '../../../../vuex/action'

export default {
  name: 'article-gao-config',
  components: {
    'vue-modal': modal
  },
  data() {
    return {
      showModal: false,
      actionType: 'CREATE', // CREATE, UPDATE
      ad: {}
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xInsert: insertBetaAd,
      xUpdate: updateBetaAd
    }
  },
  methods: {
    check() {
      var fields = ['betaId', 'betaName', 'betaDesc', 'betaType']
      for (let i = 0, len = fields.length; i < len; i++) {
        var val = this.ad[fields[i]] + ''
        if (!val.length) {
          return Promise.reject({
            error_msg: '* 标记的为必填项'
          })
        }
      }
      var files = this.$els.file.files
      if (this.actionType === 'CREATE' && files.length === 0) {
        return Promise.reject({
          error_msg: '未选择配图'
        })
      }
      return Promise.resolve()
    },
    submit() {
      this.check()
        .then(() => {
          let files = this.$els.file.files
          let formData = new FormData()
          formData.append('betaId', this.ad.betaId)
          formData.append('betaName', this.ad.betaName)
          formData.append('betaDesc', this.ad.betaDesc)
          formData.append('betaType', this.ad.betaType)
          if (files[0]) {
            formData.append('betaPic', files[0])
          }
          if (this.actionType === 'CREATE') {
            return this.xInsert(formData)
          } else {
            return this.xUpdate(formData)
          }
        })
        .then(() => {
          this.showModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
